﻿using BaseData.CommonLib.Models;
using BaseData.RazorLib.Services;
using Microsoft.AspNetCore.Components;
using Radzen;

namespace BaseData.RazorLib.Pages;

public partial class SupplierEdit
{
    private SupplierEditRequestDto _editRequestDto = new();


    [Parameter]
    public int Key { get; set; }

    [Inject] public DialogService DialogService { get; set; }

    [Inject] public ISupplierService SupplierService { get; set; }

    void CancelButtonClick()
    {
        DialogService.Close();
    }

    async Task OnSubmit()
    {

        if (Key > 0)
        {
            var result = await SupplierService.UpdateSupplier(Key, _editRequestDto);

            if (result != null && result.Succeeded)
            {
                DialogService.Close();
            }
        }
        else
        {
            var result = await SupplierService.CreateSupplier(_editRequestDto);

            if (result != null && result.Succeeded)
            {
                DialogService.Close();
            }
        }

    }

    protected override async Task OnParametersSetAsync()
    {
        _editRequestDto = new SupplierEditRequestDto();
        if (Key > 0)
        {
            var result = await SupplierService.GetSupplier(Key);
            if (result != null && result.Succeeded && result.Data != null)
            {
                _editRequestDto.Code = result.Data.Code;
                _editRequestDto.Name = result.Data.Name;
                _editRequestDto.Description = result.Data.Description;
            }
        }
    }
}